"""
给你两个 非空 的链表，表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的，并且每个节点只能存储 一位 数字。
请你将两个数相加，并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外，这两个数都不会以 0 开头。

示例1：输入：l1 = [2,4,3], l2 = [5,6,4]
输出：[7,0,8]
解释：342 + 465 = 807.
示例 2：

输入：l1 = [0], l2 = [0]
输出：[0]
示例 3：

输入：l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出：[8,9,9,9,0,0,0,1]
"""

class ListNode:
    def __init__(self, value, next=None):
        self.value = value
        self.next = next

# class Solution:
#     def add_two_nums(self, l1, l2):
#         #1.初始化工具变量
#         dumby = ListNode(0)     #虚拟头结点
#         cur = dumby             #当前结果节点指针
#         carry = 0               #进位
#
#         #2. 逐步遍历计算
#         while l1 or l2 or carry:
#             l1_val = l1.value if l1 else 0
#             l2_val = l2.value if l2 else 0
#
#             total = l1_val + l2_val + carry
#             carry = total // 10     #更新进位
#             cur.next = ListNode(total % 10)     #拼接当前位结果
#
#             #推进指针
#             cur = cur.next
#             if l1:
#                 l1 = l1.next
#             if l2:
#                 l2 = l2.next
#         return dumby.next

class Solution:
    def add_two_nums(self, l1, l2):
        #1. 初始化变量
        dumby = ListNode(0)
        cur = dumby
        carry = 0

        while l1 or l2 or carry:
            l1_val = l1.value if l1 else 0
            l2_val = l2.value if l2 else 0
            total = l1_val + l2_val + carry
            cur.next = ListNode(total % 10)
            carry = total // 10

            cur = cur.next
            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next
        return dumby.next


if __name__ == '__main__':
    s = Solution()
    # l1 = ListNode(2)
    # l1.next = ListNode(4)
    # l1.next.next = ListNode(3)
    # l2 = ListNode(5)
    # l2.next = ListNode(6)
    # l2.next.next = ListNode(4)
    # l1 = [2, 4, 3]
    # l2 = [5, 6, 4]
    # l1 = ListNode(0)
    # l2 = ListNode(0)
    l1 = ListNode(9)
    l1.next = ListNode(9)
    l1.next.next = ListNode(9)
    l1.next.next.next = ListNode(9)
    l2 = ListNode(9)
    l2.next = ListNode(9)
    l2.next.next = ListNode(9)
    res = s.add_two_nums(l1, l2)
    # print([res.value, res.next.value, res.next.next.value])
    print([res.value, res.next.value, res.next.next.value, res.next.next.next.value, res.next.next.next.next.value])
    # print([res.value])
